document.addEventListener('DOMContentLoaded', function() {
  const intervalInput = document.getElementById('interval');
  const timeUnitSelect = document.getElementById('timeUnit');
  const startBtn = document.getElementById('startBtn');
  const stopBtn = document.getElementById('stopBtn');
  const status = document.getElementById('status');
  let statusUpdateInterval;

  function updateStatus(isRunning) {
    if (isRunning) {
      startBtn.disabled = true;
      stopBtn.disabled = false;
    } else {
      status.textContent = '刷新已停止';
      startBtn.disabled = false;
      stopBtn.disabled = true;
      if (statusUpdateInterval) {
        clearInterval(statusUpdateInterval);
        statusUpdateInterval = null;
      }
    }
  }

  function formatRemainingTime(seconds) {
    if (timeUnitSelect.value === 'second') {
      return `${seconds} 秒`;
    } else {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return remainingSeconds > 0 ? 
        `${minutes} 分 ${remainingSeconds} 秒` : 
        `${minutes} 分钟`;
    }
  }

  function updateStatusDisplay() {
    chrome.tabs.query({active: true, currentWindow: true}).then(tabs => {
      if (tabs[0]) {
        chrome.runtime.sendMessage({
          action: 'getStatus',
          tabId: tabs[0].id
        }).then(response => {
          if (response && response.isRunning && response.nextRefreshTime) {
            const remainingSeconds = Math.ceil((response.nextRefreshTime - Date.now()) / 1000);
            status.textContent = `刷新进行中，还剩 ${formatRemainingTime(remainingSeconds)}`;
          }
        });
      }
    });
  }

  startBtn.addEventListener('click', function() {
    const interval = parseInt(intervalInput.value);
    const timeUnit = timeUnitSelect.value;
    
    if (interval < 1) {
      status.textContent = '请输入有效的时间间隔！';
      return;
    }

    chrome.tabs.query({active: true, currentWindow: true}).then(tabs => {
      if (tabs[0]) {
        chrome.runtime.sendMessage({
          action: 'start',
          interval: interval,
          timeUnit: timeUnit,
          tabId: tabs[0].id
        }).then(response => {
          if (response && response.success) {
            updateStatus(true);
            updateStatusDisplay();
            if (statusUpdateInterval) {
              clearInterval(statusUpdateInterval);
            }
            statusUpdateInterval = setInterval(updateStatusDisplay, 1000);
          }
        }).catch(error => {
          status.textContent = '启动失败，请重试';
          console.error('Start error:', error);
        });
      }
    });
  });

  stopBtn.addEventListener('click', function() {
    chrome.tabs.query({active: true, currentWindow: true}).then(tabs => {
      if (tabs[0]) {
        chrome.runtime.sendMessage({
          action: 'stop',
          tabId: tabs[0].id
        }).then(response => {
          if (response && response.success) {
            updateStatus(false);
          }
        }).catch(error => {
          console.error('Stop error:', error);
        });
      }
    });
  });

  // 初始化时检查状态并设置更新
  chrome.tabs.query({active: true, currentWindow: true}).then(tabs => {
    if (tabs[0]) {
      chrome.runtime.sendMessage({
        action: 'getStatus',
        tabId: tabs[0].id
      }).then(response => {
        if (response) {
          if (response.isRunning) {
            intervalInput.value = response.interval;
            timeUnitSelect.value = response.timeUnit || 'minute';
            updateStatus(true);
            updateStatusDisplay();
            if (statusUpdateInterval) {
              clearInterval(statusUpdateInterval);
            }
            statusUpdateInterval = setInterval(updateStatusDisplay, 1000);
          }
        }
      }).catch(error => {
        console.error('Get status error:', error);
      });
    }
  });

  window.addEventListener('unload', function() {
    if (statusUpdateInterval) {
      clearInterval(statusUpdateInterval);
    }
  });
});